package com.imy.luascript.viewmodel;

import com.imy.luascript.app.data.BaseListEntity;
import com.imy.luascript.app.data.BaseListResponse;
import com.imy.luascript.retrofit.ApiException;
import com.imy.luascript.retrofit.HttpListResultSubscriber;
import com.imy.luascript.retrofit.OnListRequestCallBackListener;
import com.imy.luascript.retrofit.TransformUtils;

import rx.Observable;

/**
 * @ProjectName: frame
 * @Package: com.imy.frame.viewmodel
 * @ClassName: BaseListViewModel
 * @Description:
 * @Author: Imy
 * @CreateDate: 2020/10/30 14:28
 */
public abstract class BaseListViewModel extends BaseViewModel {
    protected int page = 1;
    private static final int HAS_MORE = 1;
    private static final int NO_MORE = 0;
    private int hasMore = NO_MORE;

    public int getPage() {
        return page;
    }

    public BaseListViewModel(BaseImplView implView) {
        super(implView);
    }

    public abstract void loadData();

    public void refreshData() {
        page = 1;
        loadData();
    }

    public boolean hasNextPage() {
        return hasMore == HAS_MORE;
    }

    public void loadNextPageData() {
        page++;
        loadData();
    }


    public <T> void startListRequest(Observable<BaseListResponse<T>> request, OnListRequestCallBackListener<T> listener) {
        addSubscription(request.compose(TransformUtils.defaultSchedulers())
                .subscribe(new HttpListResultSubscriber<T>() {
                    @Override
                    public void onSuccess(BaseListEntity<T> t) {
                        hasMore = t.getMore();
                        //设置更多
                        if (listener!=null){
                            listener.onSuccess(t.getList());
                        }
                    }

                    @Override
                    public void onError(ApiException e) {
                        if (listener!=null){
                            listener.onError(e);
                        }
                    }
                }));
    }
}